const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('服务器已开启')
});
//引入封装好的myquery方法
const myquery = require('./作业修改模块化封装数据库');

//接参中间件
app.use(express.urlencoded({ extended: false}));

//注册逻辑
app.post('/register', async (req,res)=>{
  //接参
  let {username,password} = req.body;

  //判断用户名是否存在
  let sql = `SELECT * FROM member WHERE username ='${username}'`;

  let [err,result] =await myquery(sql);
  if(err){
    res.send({code:500,msg:err});
    return;
  }
  //判断用户名是否存在
  if(result.length > 0){
    res.send({code:400,msg:'用户名已存在'});
    return;
  }
  //不存在添加到列表中
  let sql1 = `insert into member (username,password) values ('${username}','${password}')`

  let [err1,result1] = await myquery(sql1);
  if(err1){
    res.send({code:500,msg:err1});
    return;
  }
  if(result1.insertId > 0){
    res.send({code:200,msg:'注册成功'});
  }else{
    res.send({code:400,msg:'请稍后再试'})
  }
})

//登录逻辑
app.post('/login',async (req,res)=>{
  let {username,password} = req.body;
  let sql = `select * from member where username = '${username}' and password = '${password}'`;
  let [err,result] = await myquery(sql);
  if(err){
    res.send({code:500,msg:err});
    return;
  }
  if (result.length > 0) {
    res.send({
      code: 200,
      msg: '登录成功'
    })
  } else {
    res.send({
      code: 400,
      msg: '用户名或密码错误'
    })
  }
})